package com.yt.user.interceptor;

import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.db.utils.RedisTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTokenUtil redisTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");

        if (token == null || !redisTokenUtil.isTokenValid(token)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            Result result = new Result<>(CodeEnum.FAIL_100004, "请先登录");
            out.write(new ObjectMapper().writeValueAsString(result));
            out.flush();
            out.close();
            return false;
        }
        return true;
    }
}